import express from "express";
import { adminGetAllLinks, getAllTips, updateLinks } from '../model/links.js';
import { findUserById } from "../model/user.js";


const adminRouter = express.Router()


adminRouter.post("/getLinks", async (req, res) => {
    const { tip } = req.body;

    const { userId } = req.cookies
    console.log(userId);

    const result = await adminGetAllLinks();
    const allTips = await getAllTips();
    const { bookmark } = await findUserById(Number(userId))
    const bookmarkArr = JSON.parse(bookmark)

    const allLinks = result.map(link => {
        const isBookmarked = bookmarkArr.includes(link.id)

        return { ...link, isBookmarked }
    })

    const data = allLinks?.map((item) => {
        const tipsArr = JSON.parse(item.tips)
        const tips = tipsArr.map(item => {
            for (let i = 0; i < allTips.length; ++i) {
                if (allTips[i].id == item) return allTips[i];
            }
        })
        return {
            ...item,
            tips: tips
        }
    }).filter((item) => {
        if (tip) {
            for (let i = 0; i < item.tips.length; ++i) {
                if (item.tips[i]?.id == tip) {
                    return true
                }
            }
            return false

        }
        else return true
    })

    res.send({
        msg: 'ok',
        data
    })
})


adminRouter.post('/updateLinks', async (req, res) => {
    const { id, status } = req.body;

    const result = await updateLinks(id, status)
    res.send({ msg: 'ok', data: result })
})





export default adminRouter